package com.xiaomi.shoppinglist

import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import android.util.Log

class ConfigureActivity : AppCompatActivity() {
    private val TAG = "ConfigureActivity"
    private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.configure_activity)

        // 初始化小部件ID
        val intent = intent
        val extras = intent.extras
        if (extras != null) {
            appWidgetId = extras.getInt(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID
            )
        }

        // 如果小部件ID无效，结束活动
        if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            Log.e(TAG, "Invalid appWidgetId")
            finish()
            return
        }

        // 设置完成按钮点击事件
        findViewById<Button>(R.id.finish_config_button).setOnClickListener {
            val context = this@ConfigureActivity

            // 初始化数据库或其他必要设置
            ShoppingListDatabase.init(context)

            // 更新小部件
            val appWidgetManager = AppWidgetManager.getInstance(context)
            ShoppingListWidget.updateAppWidget(context, appWidgetManager, appWidgetId)

            // 设置结果并结束活动
            val resultValue = Intent()
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
            setResult(RESULT_OK, resultValue)
            finish()
        }
    }
}